package com.siruier.boss.ui.dialog

import android.content.Context
import android.view.View
import com.lxj.xpopup.XPopup
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.TimePickerPopup
import com.lxj.xpopupext.view.WheelTime
import java.util.*

typealias OnTimeConfirm = (date: Date) -> Unit

fun Context.createTimePicker(builder: (TimePickerPopupExt.() -> Unit)? = null, onTimeConfirm: OnTimeConfirm? = null): TimePickerPopupExt {
    val popup = TimePickerPopupExt(this)
    builder?.let { popup.builder() }
    popup.setTimePickerListener(SimpleTimePickerListener(onTimeConfirm))
    return XPopup.Builder(this).asCustom(popup) as TimePickerPopupExt
}

class TimePickerPopupExt(context: Context) : TimePickerPopup(context) {
    var cyclic: Boolean = true
    private var mWheelTime: WheelTime? = null
    override fun onCreate() {
        super.onCreate()
        mWheelTime = javaClass.superclass?.getDeclaredField("wheelTime")?.let {
            it.isAccessible = true
            val obj = it[this] as WheelTime
            it.isAccessible = false
            obj
        }
        mWheelTime?.setCyclic(cyclic)
    }
}

private class SimpleTimePickerListener(private val onTimeConfirm: OnTimeConfirm? = null) : TimePickerListener {
    override fun onTimeChanged(date: Date) {

    }

    override fun onTimeConfirm(date: Date, view: View) {
        onTimeConfirm?.invoke(date)
    }
}